package com.jishucai.tomcat;

import com.jishucai.servlet.*;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpRequest;

import java.util.Map;


/**
 * @author qiaowang 2021/4/15
 */
public class TomcatServerHandler extends ChannelInboundHandlerAdapter {

    private Map<String, Object> registMap;

    public TomcatServerHandler(Map<String, Object> registMap) {
        this.registMap = registMap;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof HttpRequest) {
            HttpRequest request = (HttpRequest) msg;

            String servletName = request.uri().split("/")[1].toLowerCase();
            CustomServlet servnet;
            // 若注册表中存在指定的Servlet，则获取指定的servlet，否则获取默认的servlet方法
            if (registMap.containsKey(servletName)) {
                servnet =(CustomServlet) registMap.get(servletName);
            } else {
                servnet = new DefaultCusomtServlet();
            }

            CustomHttpRequest req = new DefaultCustomHttpRequest(request);
            CustomHttpResponse res = new DefaultCustomHttpResponse(request, ctx);
            if (request.method().name().equalsIgnoreCase("get")) {
                servnet.doGet(req, res);
            } else if (request.method().name().equalsIgnoreCase("POST")) {
                servnet.doPost(req, res);
            }
        }
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

